package datastructure.producerconsumer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/30 12:21
 * @description: 生产者消费者模型
 */
public class ProducerAndConsumer1 {
    public static void main(String[] args) {
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<Integer>(2);
        Thread thread1 = new Thread(()->{
            int value = 0;
            while (true){
                try {
                    blockingQueue.put(value);
                    System.out.println("生产元素: " + value);
                    value++;
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        });
        Thread thread2 = new Thread(()->{
            while (true){
                try {
                    Integer res = blockingQueue.take();
                    System.out.println("消费元素: " + res);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}
